import { Menu, Dropdown, Icon, Button, Calendar, Input, Row, Col, Checkbox, Tree } from 'antd';

const TreeNode = Tree.TreeNode;
const Item = Menu.Item;
const CheckboxGroup = Checkbox.Group;
import { WeaTools } from 'ecCom';
import equal from 'deep-equal';
import './style/index.css';
import { WeaLocaleProvider } from 'ecCom';
import { toJS } from 'mobx';

const getLabel = WeaLocaleProvider.getLabel;

class WeaDropdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      thisyear: new Date().getFullYear(),
      hrmDatas: props.datas || [],
      num: 1,
      checkArr: [],
      checkArrMultiple: {},
      checkArrMultipleSpan: {},
    };
  }

  componentWillMount() {
    const t = this.props.type;
    if (t == 'selectMultiple') {
      const { value, valueSpan, datas, keyValue } = this.props;
      const checkArrMultiple = {};
      const checkArrMultipleSpan = {};
      const ops = toJS(this.props.datas);
      for (const o of ops) {
        let checked = false;
        if (value) {
          const checkedArr = value.split(',');
          for (const c of checkedArr) {
            if (c == o.id) {
              checked = true;
            }
          }
        }
        checkArrMultiple[o.id] = checked;
        checkArrMultipleSpan[o.id] = o.name;
      }
      this.setState({ checkArrMultiple, checkArrMultipleSpan });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!equal(this.props.datas, nextProps.datas)) {
      this.setState({ hrmDatas: nextProps.datas });
    }
  }

  render() {
    const { checkArr, checkArrMultiple, hrmDatas } = this.state;
    const dateMonth = [
      [{ m: 1 }, { m: 2 }, { m: 3 }],
      [{ m: 4 }, { m: 5 }, { m: 6 }],
      [{ m: 7 }, { m: 8 }, { m: 9 }],
      [{ m: 10 }, { m: 11 }, { m: 12 }]];
    const { value, valueSpan, datas, defaultValue, type, keyValue, selectKeys = '', hrmListChange, layout = '' } = this.props;
    let menu = '';
    if (type == 'time') {
      menu = (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@8qstty`} >
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@ltwfhr`} key="crm-calendar-header">
          <div style={{ textAlign: 'center', width: '120px' }}>
            <div className="crm-calendar-header-left" onClick={this.decYear}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@dqkggq`} type="left" /></div>
            <span className="crm-calendar-header-center">{this.state.thisyear}</span>
            <div className="crm-calendar-header-right" onClick={this.addYear}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@bq7po8`} type="right" /></div>
          </div>
        </Item>
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@ztj3kx`} key="calendar-body" className="crm-calendar-body">
          {
            dateMonth.map((item, index) => (
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@d0pesd@${index}`} key={index}>
                {
                  item.map((mon, indexCol) => (<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6pndzz@${indexCol}`} span={8} onClick={() => { this.callBackMonth(mon.m); }}>{mon.m}</Col>))
                }
              </Row>
            ))
          }
        </Item>
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@9urcnd`} key="calendar-footer" className="crm-calendar-footer"><div onClick={this.callBackMonthAll}>{getLabel(332, '全部')}</div></Item>
      </Menu>);
    } else if (type == 'select') {
      menu = (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@u3g25b`} onClick={this.onSelectChange.bind(this)}>
        {
          datas.map((data, index) => (
            <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@zscmpl@${index}`} key={`item${data.id}`} >
              {data.name}
            </Item>
          ))
        }
      </Menu>);
    } else if (type == 'selectMultiple') {
      const me = this;
      menu = (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@ka1ilw`} onClick={this.onMenuClickMultiple.bind(this)}>
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@vpnrxz`} key="selectMultipleAll">{getLabel(332, '全部')}</Item>
        <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@pamlki`} />
        {
          datas.map((data, index) => (
            <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@pqm0ni@${index}`} key={data.id}>
              <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@q1afiz@${index}`} checked={checkArrMultiple[data.id]} onChange={e => me.checkboxChangeOption(data, e.target.checked)}>
                <span style={{ padding: '0 3px' }}>{data.name}</span>
              </Checkbox>
            </Item>
          ))
        }
        <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@hh0qy4`} />
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@is88ia`} key="selectMultipleOk">
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j1mg3n`} className="crm-select-multiple-btn" type="primary" size="small" onClick={() => this.markOption()}>{getLabel(826, '确定')}</Button>
        </Item>
      </Menu>);
    } else if (type == 'tag') {
      const me = this;
      menu = (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@krjfzp`} onClick={this.onMenuClick.bind(this)}>
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@n65ufe`} key="important" disabled={!selectKeys}>{getLabel(15533, '重要')}</Item>
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@kq4rqp`} key="unimportant" disabled={!selectKeys}>{getLabel(25422, '取消重要')}</Item>
        <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@ykvww2`} />
        {
          datas.map((data, index) => (
            <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@p21kt3@${index}`} key={data.key}>
              <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@3qwrdq@${index}`} onChange={() => me.checkboxChange(data.key)}>
                <span style={{ color: `${data.textColor}`, backgroundColor: `${data.labelColor}`, padding: '0 3px' }}>{data.title}</span>
              </Checkbox>
            </Item>
          ))
        }
        <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@2im7dz`} key="setting">
          <div className="crm-tag-setting-footer " >
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ehvzfw`} type="primary" size="small" disabled={!(selectKeys && `${checkArr}`)} onClick={() => this.markLable('addLabel')}>{getLabel(25432, '应用')}</Button>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d6s68a`} type="ghost" size="small" disabled={!(selectKeys && `${checkArr}`)} onClick={() => this.markLable('cancelLabel')}>{getLabel(201, '取消')}</Button>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cn89am`} type="primary" size="small" onClick={this.setting}>{getLabel(68, '设置')}</Button>
          </div>
        </Item>
      </Menu>);
    } else if (type == 'tree') {
      const me = this;
      const loop = data => data.map((item,index) => {
        if (item.children) {
          return <TreeNode ecId={`${this && this.props && this.props.ecId || ''}_TreeNode@nxr45v@${index}`} title={<span onClick={() => { this.onSelectTree(item); }}>{item.name}</span>} key={item.id}>{loop(item.children)}</TreeNode>;
        }
        return <TreeNode ecId={`${this && this.props && this.props.ecId || ''}_TreeNode@5nreww@${index}`} title={<span onClick={() => { this.onSelectTree(item); }}>{item.name}</span>} key={item.id} isLeaf={item.isLeaf} dataApi={item.getLeafApi || ''} />;
      });
      const treeNodes = loop(hrmDatas);
      menu = (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@xjj72p`} style={{ width: '155px' }}>
        <Tree ecId={`${this && this.props && this.props.ecId || ''}_Tree@tt89dw`} loadData={this.onLoadData} defaultExpandedKeys={['0']}>
          {treeNodes}
        </Tree>
      </Menu>);
    }

    let spanContent = '';
    if (value) {
      spanContent = valueSpan;
    } else {
      spanContent = defaultValue;
    }

    return (
      <Dropdown
        ecId={`${this && this.props && this.props.ecId || ''}_Dropdown@hnynh5`}
        overlay={menu}
        trigger={['hover']}
        getPopupContainer={() => (layout && document.getElementById(layout) ? document.getElementById(layout) : document.body)}
        onVisibleChange={this.handleVisibleChange}
        visible={this.state.visible}
      >
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s9o951`} type="ghost" style={{ marginLeft: 3 }} className="crm-tab-btn">
          <span className="crm-tab-span">{spanContent}</span> <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@z40kl0`} type="down" />
        </Button>
      </Dropdown>
    );
  }
    handleVisibleChange = (flag) => {
      this.setState({ visible: flag });
    }
    onMenuClick(e) {
      const { selectKeys = '' } = this.props;
      if (e.key == 'important' || e.key == 'unimportant' || e.key == 'setting') {
        this.setState({ visible: false });
      } else {
        this.setState({ visible: true });
      }
      if (e.key == 'important') {
        this.props.markTagsTo('1', selectKeys);
      }
      if (e.key == 'unimportant') {
        this.props.markTagsTo('0', selectKeys);
      }
    }
    markLable = (type) => {
      const { selectKeys = '' } = this.props;
      const { checkArr } = this.state;
      if (type == 'addLabel') {
        this.props.markToCustomTag(`${checkArr}`, selectKeys, 'addLabel');
      }
      if (type == 'cancelLabel') {
        this.props.markToCustomTag(`${checkArr}`, selectKeys, 'cancelLabel');
      }
    }
    markOption = () => {
      const keyValue = this.props.keyValue;
      const { checkArrMultiple, checkArrMultipleSpan } = this.state;
      const checkedArr = [];
      for (const o in checkArrMultiple) {
        if (checkArrMultiple[o]) {
          checkedArr.push(o);
        }
      }

      let valueSpan = '';
      if (checkedArr.length == 1) {
        valueSpan = checkArrMultipleSpan[checkedArr[0]];
      }
      if (checkedArr.length > 1) {
        const fieldTitle = this.props.defaultValue;
        valueSpan = `${fieldTitle}-${getLabel(83303, '已选')}(${checkedArr.length})`;
      }

      const params = {};
      params[keyValue] = `${checkedArr}`;
      params[`${keyValue}span`] = valueSpan;
      { typeof this.props.onChange === 'function' && this.props.onChange(params); }
    }
    checkboxChange = (key) => {
      const { checkArr } = this.state;
      const isExist = this.in_arrary(checkArr, key);
      if (isExist != 'false') {
        checkArr.splice(isExist, 1);
      } else {
        checkArr.push(key);
      }
      this.setState({ checkArr });
    }
    checkboxChangeOption = (item, checked) => {
      const checkArrMultiple = this.state.checkArrMultiple;
      checkArrMultiple[item.id] = checked;
      this.setState({ checkArrMultiple });
    }
    onMenuClickMultiple(e) {
      if (e.key == 'selectMultipleAll') {
        const checkArrMultiple = this.state.checkArrMultiple;
        for (const c in checkArrMultiple) {
          checkArrMultiple[c] = false;
        }
        this.setState({ checkArrMultiple });
        const keyValue = this.props.keyValue;
        const params = {};
        params[keyValue] = '';
        params[`${keyValue}span`] = e.item.props.children;
        { typeof this.props.onChange === 'function' && this.props.onChange(params); }
      }
    }
    in_arrary = (arr, key) => {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] == key) {
          return i;
        }
      }
      return 'false';
    }
    onSelectChange(e) {
      const { keyValue = '' } = this.props;
      const id = e.key == 'item' ? '' : e.key.replace('item', '');
      const name = e.item.props.children;
      this.setState({ value: e.item.props.children, visible: false });
      const params = {};
      params[keyValue] = id;
      params[`${keyValue}span`] = name;
      { typeof this.props.onChange === 'function' && this.props.onChange(params); }
    }
    onSelectTree = (item) => {
      const { keyValue = '' } = this.props;
      const id = item.id == '0' ? '' : item.id;
      const name = item.name;
      this.setState({ value: item.name, visible: false });
      const params = {};
      params[keyValue] = id;
      params[`${keyValue}span`] = name;
      { typeof this.props.onChange === 'function' && this.props.onChange(params); }
    }
    decYear = () => {
      this.setState({ thisyear: Number(this.state.thisyear) - 1, visible: true });
    }
    addYear = () => {
      this.setState({ thisyear: Number(this.state.thisyear) + 1, visible: true });
    }
    callBackMonth = (m) => {
      const { keyValue = '' } = this.props;
      const showMonth = `${this.state.thisyear}-${m}`;
      this.setState({ value: showMonth, visible: false });
      const params = {};
      params[keyValue] = showMonth;
      { typeof this.props.onChange === 'function' && this.props.onChange(params); }
    }
    callBackMonthAll = () => {
      const { keyValue = '' } = this.props;
      this.setState({ value: '', visible: false });
      const params = {};
      params[keyValue] = '';
      { typeof this.props.onChange === 'function' && this.props.onChange(params); }
    }
    setting = () => {
      this.props.setting();
    }
    onLoadData = (treeNode) => {
      const isChildren = treeNode.props.children || [];
      const that = this;
      const { hrmDatas } = this.state;
      if (!isChildren.length) {
        return new Promise((resolve, reject) => {
          WeaTools.callApi(treeNode.props.dataApi, 'GET', {}).then((data) => {
            const childData = data.datas;
            const treeData = [...that.state.hrmDatas];
            const loop = (data) => {
              data.forEach((item) => {
                if (treeNode.props.eventKey == item.id) {
                  item.children = childData;
                } else if (item.children) {
                  loop(item.children);
                }
              });
            };
            loop(treeData);
            that.props.hrmListChange(treeData); // 回调，更新人员列表
            that.setState({ num: that.state.num + 1, hrmDatas: treeData });
            resolve(data.datas);
          });
        });
      }
      return false;
    }
}

export default WeaDropdown;
